"use client"
import classNames from "classnames"
import { ReactNode, createContext, useContext, useState } from "react"
import "./style.css"

// 1. 创建上下文（仅存必要状态）
const MyTabsContext = createContext<{
  activeValue: string
  setActiveValue: (value: string) => void
}>({ activeValue: '', setActiveValue: () => {} })

// 2. 标签触发按钮（修复变量冲突）
interface MyTabsListTriggerProps {
  className?: string
  children: ReactNode
  value: string
}
export const MyTabsListTrigger = ({ className, children, value }: MyTabsListTriggerProps) => {
  const { activeValue, setActiveValue } = useContext(MyTabsContext)
  // 修复：直接使用上下文的 setActiveValue，无需重复定义（避免死循环）
  return (
    <button
      className={classNames(
        'my-tabs-list-trigger',
        className,
        value === activeValue && 'active'
      )}
      onClick={() => setActiveValue(value)} // 直接调用上下文的方法
    >
      {children}
    </button>
  )
}

// 3. 标签列表容器（无多余逻辑）
interface MyTabsListProps {
  className?: string
  children: ReactNode
}
export const MyTabsList = ({ className, children }: MyTabsListProps) => {
  return (
    // <StickyBox>
    <div className={classNames('my-tabs-list mb-content-gap-y md:mb-content-gap-y-md', className)}>{children}</div>
    // </StickyBox>
  )
}

// 4. 标签内容（添加显示隐藏逻辑）
interface MyTabsContentProps {
  className?: string
  children: ReactNode
  value: string
}
export const MyTabsContent = ({ className, children, value }: MyTabsContentProps) => {
  const { activeValue } = useContext(MyTabsContext)
  const isActive = value === activeValue
  return (
    <div
      className={classNames(
        'my-tabs-content',
        className,
        !isActive && 'hidden' // 未激活时隐藏
      )}
    >
      {children}
    </div>
  )
}

// 5. 核心标签容器（简化状态管理）
interface Props {
  className?: string
  children: ReactNode
  activeValue: string
}
export const MyTabs = ({ className, children, activeValue }: Props) => {
  const [currentActive, setCurrentActive] = useState(activeValue)
  return (
    <MyTabsContext.Provider value={{ activeValue: currentActive, setActiveValue: setCurrentActive }}>
      <div className={classNames('my-tabs', className)}>{children}</div>
    </MyTabsContext.Provider>
  )
}